package wec_wallet.ebo.com.intercept;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import bassproject.ebo.com.ebobass.utils.Lg;

/**
 * 来去电监听服务
 */

public class PhoneListenService extends Service {

    public static final String ACTION_REGISTER_LISTENER = "action_register_listener";
    public   String data = "";

    private MyBinder mBinder = new MyBinder();
    public class MyBinder extends Binder {
       public PhoneListenService getService() {
            return PhoneListenService.this;
        }
        public void setData(String data){
            PhoneListenService.this.data = data;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Lg.d("onCreate");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Lg.d("onStartCommand action: " + intent.getAction() + " flags: " + flags + " startId: " + startId);
        return super.onStartCommand(intent, flags, startId);
    }


    TelephonyManager telephonyManager;
    CustomPhoneStateListener customPhoneStateListener;

    private void registerPhoneStateListener() {
        customPhoneStateListener = new CustomPhoneStateListener(this);
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            telephonyManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        Lg.d("onbind");
        String action = intent.getAction();
        if (action.equals(ACTION_REGISTER_LISTENER)) {
            registerPhoneStateListener();
        }
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Lg.d("onUnbind");
        if (telephonyManager != null && customPhoneStateListener != null) {
            telephonyManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Lg.d("onRebind action: " + intent.getAction());
        super.onRebind(intent);
    }

    @Override
    public void onDestroy() {
        Lg.d("onDestroy");
        if (telephonyManager != null && customPhoneStateListener != null) {
            telephonyManager.listen(customPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
        super.onDestroy();
    }


}
